<?php
/**
 *@file articletag.php
 *@author Zhe.Zhou(zhouzhe@haibao.com)
 *@date 2015-4-20 下午8:18:03
 *@brief  
 */
namespace haibao\cms\data;


class ArticleTag extends \haibao\cms\data\BaseMysql{
    
	public function __construct(){
		parent::__construct('\haibao\cms\model\data\ArticleTag');
	}

	public function getTagsByArticleIds($articleIds,$getPrimaiy = false,$inTags){
		$str = implode(',',$articleIds);
		$str = preg_replace('/(\d+)/','%s',$str);
		$andStr = $inTags ? ' and TagId in ('.implode(',',$inTags).') ' :'';
		$sql = 'SELECT ArticleId,TagId,IsPrimaiy
 				FROM ArticleTag
 				WHERE ArticleId in ('.$str.')'.$andStr;
		$result = $this->query($sql,$articleIds);
		$articleTags = $articlePrimaiyTags = array();
		if($result){
			while($result->fetch_assoc()){
				$articleTags[$result->getData('ArticleId')][] = $result->getData('TagId');
				if($result->getData('IsPrimaiy') == \haibao\cms\model\data\ArticleTag::PRIMAIY_IS){
					$articlePrimaiyTags[$result->getData('ArticleId')] = $result->getData('TagId');
				}
			}
		}
		if($getPrimaiy){
			return $articlePrimaiyTags;
		}else{
			return $articleTags;
		}
	}

	public function updateTagTree($tagTreeArr){
		$whenStr = $inStr =  '';
		$sqlArr = array();
		foreach($tagTreeArr as $key=>$value){
			$whenStr .= " WHEN %s THEN %s ";
			$inStr .= "%s,";
			$sqlArr[] = $key;
			$sqlArr[] = $value;
		}
		$sql = "UPDATE ArticleTag
    				SET TagTree = CASE TagId".
					$whenStr
					."END
				WHERE TagId IN (".trim($inStr,',').")";

		$sqlArr = array_merge($sqlArr,array_keys($tagTreeArr));
		$this->query($sql,$sqlArr);
	}
}